<?php
/**
 * initAddUserForm()
 *
 * @return
 */
function initAddUserForm()
{
    $form = new zeus_quickform(array("id" => "sv-form",
            "name" => "sv-form",
            "action" => "javascript:void(null)",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    return $form;
}
/**
 * initEditUserForm()
 *
 * @return
 */
function initEditUserForm()
{
    $form = new zeus_quickform(array("id" => "sv-form",
            "name" => "sv-form",
            "action" => "javascript:void(null)",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    return $form;
}
/**
 * initEditUserFormElements()
 *
 * @return
 */
function initEditUserFormElements()
{
    $elements = array(
        array("label" => array("for" => "user_name", "name" => _e("Username (required)")),
            "form" => array("type" => "text", "options" => array("id" => "user_name", "name" => "user_name", "value" => $_POST['user_name']))),
        array("label" => array("for" => "pass1", "name" => _e("Password (required)")),
            "form" => array("type" => "text", "options" => array("id" => "pass1", "name" => "pass1", "value" => $_POST['pass1']))),
        array("label" => array("for" => "pass2", "name" => _e("Retype Password (required)")),
            "form" => array("type" => "text", "options" => array("id" => "pass2", "name" => "pass2", "value" => $_POST['pass2']))),
        array("label" => array("for" => "real_name", "name" => _e("Real Name")),
            "form" => array("type" => "text", "options" => array("id" => "real_name", "name" => "real_name", "value" => $_POST['real_name']))),
        array("label" => array("for" => "id_card", "name" => _e("Id Card (required)")),
            "form" => array("type" => "text", "options" => array("id" => "id_card", "name" => "id_card", "value" => $_POST['id_card']))),
        array("label" => array("for" => "cell_phone", "name" => _e("Cell Phone")),
            "form" => array("type" => "text", "options" => array("id" => "cell_phone", "name" => "cell_phone", "value" => $_POST['cell_phone']))),
        array("label" => array("for" => "email", "name" => _e("Email")),
            "form" => array("type" => "text", "options" => array("id" => "email", "name" => "email", "value" => $_POST['email'])))
        );
    return $elements;
}
/**
 * initAddUserFormElements()
 *
 * @return
 */
function initAddUserFormElements()
{
    $elements = array(
        array("label" => array("for" => "user_name", "name" => _e("Username (required)")),
            "form" => array("type" => "text", "options" => array("id" => "user_name", "name" => "user_name", "value" => $_POST['user_name']))),
        array("label" => array("for" => "pass1", "name" => _e("Password (required)")),
            "form" => array("type" => "text", "options" => array("id" => "pass1", "name" => "pass1", "value" => $_POST['pass1']))),
        array("label" => array("for" => "pass2", "name" => _e("Retype Password (required)")),
            "form" => array("type" => "text", "options" => array("id" => "pass2", "name" => "pass2", "value" => $_POST['pass2'])))
        );
    return $elements;
}

/**
 * showUserGridRow()
 *
 * @param array $aUser
 * @param string $sStyle
 * @return
 */
function showUserGridRow($oGrid, $aUser = array(), $sStyle = "")
{
    $row[] = "<tr id='user-" . $aUser['user_id'] . $sStyle . ">";
    if ($oGrid->bDelete) {
        $row[] = "<th scope='row' class='check-column'><input type='checkbox' name='delete[]' value='" . $aUser['user_id'] . "' /></th>" . $wrap;
    } else {
        $row[] = "";
    }
    if ($oGrid->bEdit) {
        $edit = "?action=edit_user&user_id=" . $aUser['user_id'];
    } elseif ($oGrid->bView) {
        $edit = "?action=view_user&user_id=" . $aUser['user_id'];
    } else {
        $edit = "#";
    }
    $row[] = "<td>" . $aUser['signup_time'] . "</td>";
    $row[] = "<td><strong><a href='" . $_SERVER['PHP_SELF'] . $edit . "'>" . $aUser['user_name'] . "</a></strong></td>";
    $row[] = "<td>" . $aUser['real_name'] . "</td>";
    $row[] = "<td>" . $aUser['sex_id'] . "</td>";
    $row[] = "<td>" . $aUser['cell_phone'] . "</td>";
    $row[] = "<td><a href='mailto:" . $aUser['email'] . "'>" . $aUser['email'] . "</a></td>";
    $row[] = "<td>" . $aUser['role_id'] . "</td>";
    $row[] = "<td>" . $aUser['last_login_time'] . "</td>";
    $row[] = "<td>" . $aUser['is_enable'] . "</td>";
    $row[] = "</tr>";
    return implode("\n\t", $row);
}

/**
 * init_user_grid()
 *
 * @return
 */
function initUserGrid()
{
    // Create heap
    if ($_SESSION['update_user_grid_view'] && isExistTable("user_grid_view")) {
        emptyTable("user_grid_view");
        updateUserGridHeap();
    } else {
        createUserGridHeap();
        updateUserGridHeap();
    }
    $_SESSION['update_user_grid_view'] = false;
    // Init grid
    $grid = new zeus_datagrid();
    $grid->oForm = new zeus_quickform(array("id" => "posts-filter", "method" => "get"));
    if (is_object($grid)) {
        // Set grid title
        $grid->sGridTitle = _e("Manage Users");
        // Set id column
        $grid->sIdColumn = DB_PREFIX . "user_grid_view.user_id";
        // Set operater
        $grid->bDelete = can_operate('del_user', $_SESSION['user_id']);
        $grid->bView = can_operate('view_user', $_SESSION['user_id']);
        $grid->bEdit = can_operate('edit_user', $_SESSION['user_id']);
        $grid->bAdd = can_operate('add_user', $_SESSION['user_id']);
        $grid->bDebug = false;
        // Set submenu
        $grid->aSubMenu = array(_e('All Users') => null,
            _e('Actived') => "1",
            _e('Locked') => "0",
            );
        // Set table
        $grid->sTable = array(DB_PREFIX . 'user_grid_view');
        // Set column display name
        $grid->aColumn = array("checkbox" => array("name" => $grid->oForm->addElement("checkbox", array("onclick" => "checkAll();return false"))),
            "user_id" => array("name" => _e("Signup Time"), "field" => "signup_time"),
            "user_name" => array("name" => _e("Username"), "field" => "user_name"),
            "real_name" => array("name" => _e("Real Name"), "field" => "real_name") ,
            "sex" => array("name" => _e("Sex"), "field" => "sex_id"),
            "cell_phone" => array("name" => _e("Cell Phone"), "field" => "cell_phone"),
            "email" => array("name" => _e("Email"), "field" => "email"),
            "role" => array("name" => _e("Role"), "field" => "role_id"),
            "last_login_time" => array("name" => _e("Last Login Time"), "field" => "last_login_time"),
            "status" => array("name" => _e("Status"), "field" => "is_enable")
            );
        if (!$grid->bDelete) {
            $grid->aColumn = array_slice($grid->aColumn, 1);
        } else {
            zeus_do_nothing();
        }
        // Set fields
        $grid->aField = array(
            DB_PREFIX . "user_grid_view.user_id",
            DB_PREFIX . "user_grid_view.user_name",
            DB_PREFIX . "user_grid_view.is_enable",
            DB_PREFIX . "user_grid_view.role_id",
            DB_PREFIX . "user_grid_view.real_name",
            DB_PREFIX . "user_grid_view.sex_id",
            DB_PREFIX . "user_grid_view.cell_phone",
            DB_PREFIX . "user_grid_view.email",
            DB_PREFIX . "user_grid_view.last_login_time",
            DB_PREFIX . "user_grid_view.signup_time",
            );
        // Set select
        $firstentry = _e('Show All Role Users');
        $options = getAllPower();
        $options[0] = $firstentry;
        $grid->aSelect = array(
            array("property" => array("name" => "filtrate_role"),
                "options" => $options,
                "current" => $_GET['filtrate_role']),
            array("property" => array("name" => "filtrate_signuptime"),
                "options" => array("-1" => _e("Show All Signup Users"),
                    "1" => _e("The Last Three Days"),
                    "2" => _e("The Last Week"),
                    "3" => _e("The Last Two Weeks"),
                    "4" => _e("The Last Month"),
                    "5" => _e("The Last Six Months"),
                    "6" => _e("The Last Year")
                    ),
                "current" => $_GET['filtrate_signuptime']));
        // Set match
        $grid->sMatch = null;
        // Set whole only
        $grid->bWholeOnly = false;
        // Set order
        $grid->sOrder = isset($_GET['order'])?$_GET['order']:null;
        // Sett order type
        $grid->sOrderType = isset($_GET['type'])?$_GET['type']:null;
        // Set status
        if (isset($_GET['status']) && null != $_GET['status']) {
            switch ($_GET['status']) {
                case "1":
                case "0":
                    $grid->bWholeOnly = true;
                    $grid->sFilter = $_GET['status'];
                    $grid->sFilterField = DB_PREFIX . "user_grid_view.is_enable";
                    break;
                default:
                    $grid->sFilterField = null;
                    $grid->sFilter = null;
                    break;
            }
        }
        // Set search
        elseif (isset($_GET['submit']) && (_e('Search')) == $_GET['submit']) {
            $grid->sFilter = $_GET['search'];
        }
        // Set filtrate field
        elseif (isset($_GET['filtrate']) && _e('Filtrate') == $_GET['filtrate']) {
            if (isset($_GET['filtrate_role']) && null != $_GET['filtrate_role']) {
                switch ($_GET['filtrate_role']) {
                    case "-1":
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                    case "9":
                        $grid->sFilter = $_GET['filtrate_role'];
                        $grid->sFilterField = DB_PREFIX . "user_grid_view.role_id";
                        break;
                    default:
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                }
            } else {
                $grid->sFilterField = null;
                $grid->sFilter = null;
            }
        } else {
            $grid->sFilterField = null;
            $grid->sFilter = null;
        }
    } else {
        zeus_do_nothing();
    }
    return $grid;
}
/**
 * createNewPwd()
 *
 * @return
 */
function createNewPwd()
{
    $pwd['real'] = substr(md5(rand(100, 999)), rand(0, 26), 6);
    $pwd['md5'] = md5($pwd['real']);
    return $pwd;
}
/**
 * getUserValid()
 *
 * @param string $sUserName
 * @return
 */
function getUserValid($sUserName = "")
{
    if (isset($sUserName) && null != $sUserName) {
        $sql = "SELECT is_enable FROM " . DB_PREFIX . "user_auth WHERE user_name='" . $sUserName . "';";
        $result = zeus_sql_query($sql, false);
        return ("1" == $result['is_enable'])?true:false;
    } else {
        return false;
    }
}
/**
 * getUserId()
 *
 * @param string $sUserName
 * @return
 */
function getUserId($sUserName = "")
{
    if (isset($sUserName) && null != $sUserName) {
        $sql = "SELECT user_id FROM " . DB_PREFIX . "user_auth WHERE user_name='" . $sUserName . "';";
        $result = zeus_sql_query($sql, false);
        return (isset($result['user_id']))?$result['user_id']:false;
    } else {
        return false;
    }
}
/**
 * getLatestUserId()
 *
 * @return
 */
function getLatestUserId()
{
    $sql = "SELECT MAX(user_id) FROM " . DB_PREFIX . "user_auth";
    $result = zeus_sql_query($sql, false);
    $max = "MAX(user_id)";
    if (isset($result)) {
        return $result[$max];
    } else {
        return false;
    }
}
/**
 * addNewUserAuth()
 *
 * @param array $aAuth
 * @return
 */
function addNewUserAuth($sUserId = "", $aAuth = array())
{
    if (isset($aAuth) && null != $aAuth) {
        $field[] = 'user_id';
        $value[] = $sUserId;
        foreach($aAuth AS $auth_key => $auth_value) {
            $field[] = $auth_key;
            $value[] = $auth_value;
        }
        $sql = "INSERT INTO " . DB_PREFIX . "user_auth (" . implode(",", $field) . ")"
         . " VALUES ('" . implode("','", $value) . "')";
        return $sql;
    } else {
        return false;
    }
}
/**
 * addNewUserDetail()
 *
 * @param array $aDetail
 * @return
 */
function addNewUserDetail($sUserId = "", $aDetail = array())
{
    if (isset($aDetail) && null != $aDetail) {
        $field[] = 'user_id';
        $value[] = $sUserId;
        foreach($aDetail AS $detail_key => $detail_value) {
            $field[] = $detail_key;
            $value[] = $detail_value;
        }
        $sql = "INSERT INTO " . DB_PREFIX . "user_detail (" . implode(",", $field) . ")"
         . " VALUES ('" . implode("','", $value) . "')";
        return $sql;
    } else {
        return false;
    }
}
/**
 * addNewUser()
 *
 * @param array $aAuth
 * @param array $aDetail
 * @return
 */
function addNewUser($aUserInfo = array())
{
    $aSql[] = "LOCK TABLE " . DB_PREFIX . "user_auth WRITE," . DB_PREFIX . "user_detail WRITE";
    $newUserId = getLatestUserId() + 1;
    $aSql[] = addNewUserAuth($newUserId, $aUserInfo['auth']);
    $aSql[] = addNewUserDetail($newUserId, $aUserInfo['detail']);
    $aSql[] = "UNLOCK TABLES";
    $sql = implode(";", array_filter($aSql));
    if (zeus_sql_query($sql, false)) {
        return true;
    } else {
        return false;
    }
}
/**
 * getUserInfo()
 *
 * @param string $sUserId
 * @return
 */
function getUserInfo($sUserId = "")
{
    if (isset($sUserId) && "" != $sUserId) {
        $sql = "SELECT * FROM " . DB_PREFIX . "user_auth WHERE user_id='" . $sUserId . "'";
        $auth = zeus_sql_query($sql, false);
        $sql = "SELECT * FROM " . DB_PREFIX . "user_detail WHERE user_id='" . $sUserId . "'";
        $detail = zeus_sql_query($sql, false);
        if (isset($detail) && isset($auth)) {
            $info = array_merge($auth, $detail);
            return $info;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * getTheUserPwd()
 *
 * @param string $sUserId
 * @return
 */
function getTheUserPwd($sUserId = "")
{
    if (isset($sUserId) && "" != $sUserId) {
        $sql = "SELECT user_pwd FROM " . DB_PREFIX . "user_auth WHERE user_id='" . $sUserId . "'";
        $result = zeus_sql_query($sql, false);
        if (isset($result) && null != $result) {
            return $result['user_pwd'];
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * getTheUserRoleId()
 *
 * @param string $sUserId
 * @return
 */
function getTheUserRoleId($sUserId = "")
{
    if (isset($sUserId) && "" != $sUserId) {
        $sql = "SELECT role_id FROM " . DB_PREFIX . "user_auth WHERE user_id='" . $sUserId . "'";
        $result = zeus_sql_query($sql, false);
        if (isset($result) && null != $result) {
            return $result['role_id'];
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * getTheUserEnable()
 *
 * @param string $sUserId
 * @return
 */
function getTheUserEnable($sUserId = "")
{
    if (isset($sUserId) && "" != $sUserId) {
        $sql = "SELECT is_enable FROM " . DB_PREFIX . "user_auth WHERE user_id='" . $sUserId . "'";
        $result = zeus_sql_query($sql, false);
        if (isset($result) && null != $result) {
            return $result['is_enable'];
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * generateUserName()
 *
 * @param integer $max
 * @return
 */
function generateUserName($iMax = 100)
{
    $surfix = range(1, $iMax);
    foreach($surfix AS $value) {
        $name[] = "user_" . $value;
    }
    return implode("<br>", $name);
}
/**
 * updateTheUser()
 *
 * @param array $aUser
 * @return
 */
function updateTheUser($aUser = array())
{
    // Get user id
    switch ($_GET['action']) {
        case 'edit_user':
            $user_id = $_GET['user_id'];
            break;
        default:
            $user_id = $_SESSION['user_id'];
            $aUser['is_enable'] = getTheUserEnable($user_id);
            $aUser['role_id'] = getTheUserRoleId($user_id);
            break;
    }
    // Get user password
    $old_pwd = getTheUserPwd($user_id);
    if (null == $aUser['user_pwd1'] && null == $aUser['user_pwd2']) {
        $new_pwd = $old_pwd;
    } elseif ("" != $aUser['user_pwd2'] && $aUser['user_pwd1'] == $aUser['user_pwd2']) {
        $new_pwd = md5($aUser['user_pwd2']);
    } else {
        $new_pwd = $old_pwd;
    }
    $sql[] = "UPDATE " . DB_PREFIX . "user_auth SET user_pwd='" . $new_pwd . "',role_id='" . $aUser['role_id'] . "',is_enable='" . $aUser['is_enable'] . "' WHERE user_id='" . $user_id . "'";
    $sql[] = "UPDATE " . DB_PREFIX . "user_detail SET real_name='" . $aUser['real_name'] . "',sex_id='" . $aUser['sex_id'] . "',id_card='" . $aUser['id_card'] . "',email='" . $aUser['email'] . "',im='" . $aUser['im'] . "',address='" . $aUser['address'] . "',homepage='" . $aUser['homepage'] . "',cell_phone='" . $aUser['cell_phone'] . "',home_phone='" . $aUser['home_phone'] . "' WHERE user_id='" . $user_id . "'";
    $query = implode(";", $sql);
    if (zeus_sql_exec($query, false)) {
        $_SESSION['update_user_grid_view'] = true;
        return true;
    } else {
        return false;
    }
}
/**
 * updateLastLoginTime()
 *
 * @return
 */
function updateLastLoginTime()
{
    $timezone_identifier = "Asia/Shanghai";
    date_default_timezone_set($timezone_identifier);  
    $sql = "UPDATE " . DB_PREFIX . "user_detail SET last_login_time='" . date("Y-m-d H:i:s") . "' WHERE user_id='" . $_SESSION['user_id'] . "'";
    if (zeus_sql_exec($sql, false)) {
        return true;
    } else {
        return false;
    }
}

?>